"""
简单的DeepSeek API测试脚本 - 通过monkey patch禁用代理
"""
import os
import sys
import importlib

# 1. 在导入OpenAI之前，先尝试修复代理问题
try:
    # 清除环境变量中的代理设置
    for proxy_var in ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy']:
        if proxy_var in os.environ:
            print(f"删除环境变量: {proxy_var}")
            del os.environ[proxy_var]
            
    # 使用monkey patch覆盖httpx创建client的行为，阻止传入proxies参数
    import httpx
    original_client = httpx.Client
    
    class ClientWithoutProxies(original_client):
        def __init__(self, **kwargs):
            if 'proxies' in kwargs:
                print("⚠️ 拦截并移除了proxies参数")
                del kwargs['proxies']
            super().__init__(**kwargs)
    
    # 替换httpx.Client
    httpx.Client = ClientWithoutProxies
    
    # 如果AsyncClient也有同样问题，也替换它
    original_async_client = httpx.AsyncClient
    
    class AsyncClientWithoutProxies(original_async_client):
        def __init__(self, **kwargs):
            if 'proxies' in kwargs:
                print("⚠️ 拦截并移除了异步客户端的proxies参数")
                del kwargs['proxies']
            super().__init__(**kwargs)
    
    # 替换httpx.AsyncClient
    httpx.AsyncClient = AsyncClientWithoutProxies
    
    print("✅ 成功应用monkey patch")
    
except Exception as e:
    print(f"⚠️ 应用monkey patch失败: {str(e)}")

# 2. 现在导入OpenAI
from openai import OpenAI

# 直接设置API密钥
API_KEY = "sk-ae300ec48152480985532799aecd4f1a"
BASE_URL = "https://api.deepseek.com"

try:
    print("\n创建OpenAI客户端...")
    # 仅传入必要的参数
    client = OpenAI(
        api_key=API_KEY,
        base_url=BASE_URL
    )
    
    print("发送测试请求...")
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "你是一个有帮助的助手"},
            {"role": "user", "content": "你好，这是一条测试消息"},
        ],
        temperature=0.1,
        max_tokens=100
    )
    
    print(f"\n响应内容: {response.choices[0].message.content}")
    
    if hasattr(response, 'usage'):
        print(f"\n令牌使用: 提示词={response.usage.prompt_tokens}, "
              f"完成={response.usage.completion_tokens}, "
              f"总计={response.usage.total_tokens}")
    
    print("\n✅ 测试成功!")
    
except Exception as e:
    print(f"\n❌ 测试失败: {str(e)}")
    
    # 打印更详细的错误信息
    import traceback
    print("\n详细错误信息:")
    traceback.print_exc() 